package com.gl.basis.zuul.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;


public class RequestUtils {

	// 获取请求参数，适用于POST请求/GET请求，以及参数拼接在URL后面的POST请求
	public static String getRequestParams(RequestContext requestContext, HttpServletRequest request) {
		String requestParams = null;
		String requestMethod = request.getMethod();
		StringBuilder params = new StringBuilder();
		Enumeration<String> names = request.getParameterNames();
		if (requestMethod.equals("GET")) {
			while (names.hasMoreElements()) {
				String name = (String) names.nextElement();
				params.append(name);
				params.append("=");
				params.append(request.getParameter(name));
				params.append("&");
			}
			requestParams = params.delete(params.length() - 1, params.length()).toString();
		} else {
			Map<String, String> res = new HashMap<>();
			Enumeration<?> temp = request.getParameterNames();
			if (null != temp) {
				while (temp.hasMoreElements()) {
					String en = (String) temp.nextElement();
					String value = request.getParameter(en);
					res.put(en, value);
				}
				requestParams = JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(requestParams) || "{}".equals(requestParams)) {
				BufferedReader br = null;
				StringBuilder sb = new StringBuilder("");
				try {
					br = request.getReader();
					String str;
					while ((str = br.readLine()) != null) {
						sb.append(str);
					}
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (null != br) {
						try {
							br.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
				requestParams = sb.toString();
			}
		}
		return requestParams;
	}

	
}
